/*
 *  Copyright 2011 cubika.
 * 
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 * 
 *       http://www.apache.org/licenses/LICENSE-2.0
 * 
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *  under the License.
 */

package com.seminario.spring.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.springframework.transaction.annotation.Transactional;

/**
 *
 * @author Zeta
 */
public abstract class DAOImpl<T> implements DAO<T> {

    @PersistenceContext
    protected EntityManager entityManager;

    @SuppressWarnings({ "unchecked", "null" })
    @Override
    @Transactional
    public T findById(Class clazz , Object id) {
        return (T) entityManager.find(clazz, id);
    }

    @Override
    @Transactional
    public T merge(T entity) {
        return entityManager.merge(entity);
    }

    @Override
    @Transactional
    public T persist(T entity) {
        entityManager.persist(entity);
        return entity;
    }

    @Override
    @Transactional
    public void remove(T entity) {
        entityManager.remove(entity);
    }

    /**
     * Obtains and returns the current hibernate session.
     *
     * @return the current hibernate session.
     */
    protected EntityManager getEntityManager() {
        return entityManager;
    }

    /**
     * This method must return the entity's class the DAO handles.
     *
     * @return The class the entity's DAO handles.
     */
    protected abstract Class<T> getEntityClass();

    @Override
    public abstract List<T> getAll();
}

